import 'dart:async';
import 'package:ffmpeg_kit_flutter/ffmpeg_kit.dart';
import 'package:ffmpeg_kit_flutter/ffprobe_kit.dart';
import 'package:ffmpeg_kit_flutter/return_code.dart';
import 'package:ffmpeg_kit_flutter/session.dart';
import 'package:ffmpeg_kit_flutter/statistics.dart';
import 'models/player_state.dart';
import 'models/media_info.dart';
import 'models/player_config.dart';

class FFmpegKitEngine {
  // 流控制器
  final StreamController<PlayerState> _stateController = StreamController.broadcast();
  final StreamController<double> _timeController = StreamController.broadcast();
  final StreamController<MediaInfo> _mediaInfoController = StreamController.broadcast();
  final StreamController<String> _errorController = StreamController.broadcast();
  
  // 当前状态
  PlayerState _currentState = PlayerState.idle;
  double _currentTime = 0.0;
  double _duration = 0.0;
  String? _currentFilePath;
  MediaInfo? _mediaInfo;
  Session? _currentSession;
  
  // 播放控制
  bool _isPlaying = false;
  bool _isPaused = false;
  Timer? _progressTimer;
  
  FFmpegKitEngine() {
    _setupFFmpegKitCallbacks();
  }
  
  void _setupFFmpegKitCallbacks() {
    // 设置统计信息回调
    FFmpegKitConfig.enableStatisticsCallback((Statistics statistics) {
      if (_isPlaying && !_isPaused) {
        _currentTime = statistics.getTime() / 1000.0; // 转换为秒
        _timeController.add(_currentTime);
      }
    });
    
    // 设置会话回调
    FFmpegKitConfig.enableSessionCallback((Session session) {
      final returnCode = session.getReturnCode();
      if (ReturnCode.isSuccess(returnCode)) {
        _stateController.add(PlayerState.stopped);
        _isPlaying = false;
        _isPaused = false;
      } else if (ReturnCode.isCancel(returnCode)) {
        _stateController.add(PlayerState.paused);
        _isPaused = true;
      } else {
        _errorController.add('FFmpeg执行失败: ${session.getFailStackTrace()}');
        _stateController.add(PlayerState.error);
      }
    });
  }
  
  // 基本控制方法
  Future<bool> loadMedia(String filePath, {PlayerConfig? config}) async {
    try {
      _currentFilePath = filePath;
      _currentState = PlayerState.loading;
      _stateController.add(_currentState);
      
      // 获取媒体信息
      final mediaInfo = await _getMediaInfo(filePath);
      if (mediaInfo != null) {
        _mediaInfo = mediaInfo;
        _duration = mediaInfo.duration.inSeconds.toDouble();
        _mediaInfoController.add(mediaInfo);
        
        _currentState = PlayerState.idle;
        _stateController.add(_currentState);
        return true;
      }
      
      _errorController.add('无法获取媒体信息');
      _currentState = PlayerState.error;
      _stateController.add(_currentState);
      return false;
    } catch (e) {
      _errorController.add('加载媒体文件失败: $e');
      _currentState = PlayerState.error;
      _stateController.add(_currentState);
      return false;
    }
  }
  
  Future<MediaInfo?> _getMediaInfo(String filePath) async {
    try {
      final session = await FFprobeKit.getMediaInformation(filePath);
      final information = session.getMediaInformation();
      
      if (information != null) {
        final duration = information.getDuration();
        final width = information.getWidth();
        final height = information.getHeight();
        final bitrate = information.getBitrate();
        final codec = information.getVideoCodec();
        
        return MediaInfo(
          title: _extractFileName(filePath),
          artist: '',
          album: '',
          duration: Duration(milliseconds: duration?.toInt() ?? 0),
          width: width?.toInt() ?? 0,
          height: height?.toInt() ?? 0,
          frameRate: 30.0, // 默认帧率
          codec: codec ?? 'unknown',
          bitrate: bitrate?.toInt() ?? 0,
        );
      }
    } catch (e) {
      print('获取媒体信息失败: $e');
    }
    return null;
  }
  
  String _extractFileName(String filePath) {
    final parts = filePath.split('/');
    return parts.isNotEmpty ? parts.last : 'Unknown';
  }
  
  Future<bool> play() async {
    if (_currentFilePath == null) {
      _errorController.add('请先加载媒体文件');
      return false;
    }
    
    try {
      if (_isPaused) {
        // 恢复播放
        _isPaused = false;
        _isPlaying = true;
        _currentState = PlayerState.playing;
        _stateController.add(_currentState);
        _startProgressTimer();
        return true;
      }
      
      // 开始播放
      _currentState = PlayerState.playing;
      _stateController.add(_currentState);
      
      // 使用FFmpeg播放视频（这里简化处理）
      final command = '-i "$_currentFilePath" -f null -';
      _currentSession = await FFmpegKit.executeAsync(command);
      
      _isPlaying = true;
      _startProgressTimer();
      return true;
    } catch (e) {
      _errorController.add('播放失败: $e');
      _currentState = PlayerState.error;
      _stateController.add(_currentState);
      return false;
    }
  }
  
  Future<bool> pause() async {
    if (!_isPlaying) {
      return false;
    }
    
    try {
      // 取消当前会话
      if (_currentSession != null) {
        await FFmpegKit.cancel();
      }
      
      _isPaused = true;
      _isPlaying = false;
      _currentState = PlayerState.paused;
      _stateController.add(_currentState);
      _stopProgressTimer();
      return true;
    } catch (e) {
      _errorController.add('暂停失败: $e');
      return false;
    }
  }
  
  Future<bool> stop() async {
    try {
      // 取消当前会话
      if (_currentSession != null) {
        await FFmpegKit.cancel();
      }
      
      _isPlaying = false;
      _isPaused = false;
      _currentTime = 0.0;
      _currentState = PlayerState.stopped;
      _stateController.add(_currentState);
      _stopProgressTimer();
      return true;
    } catch (e) {
      _errorController.add('停止失败: $e');
      return false;
    }
  }
  
  Future<bool> seek(double timeSeconds) async {
    if (_currentFilePath == null) {
      return false;
    }
    
    try {
      _currentTime = timeSeconds;
      _timeController.add(_currentTime);
      
      // 这里简化处理，实际应该重新开始播放
      if (_isPlaying) {
        await stop();
        await play();
      }
      
      return true;
    } catch (e) {
      _errorController.add('跳转失败: $e');
      return false;
    }
  }
  
  Future<void> setVolume(double volume) async {
    // FFmpegKit的音量控制需要重新编码，这里简化处理
    print('设置音量: $volume');
  }
  
  Future<void> setHardwareDecode(bool enable) async {
    // 硬件解码设置
    print('硬件解码: $enable');
  }
  
  Future<void> setBatteryOptimization(bool enable) async {
    // 省电模式设置
    print('省电模式: $enable');
  }
  
  Future<void> setMemoryLimit(int mbLimit) async {
    // 内存限制设置
    print('内存限制: ${mbLimit}MB');
  }
  
  void _startProgressTimer() {
    _stopProgressTimer();
    _progressTimer = Timer.periodic(const Duration(milliseconds: 100), (timer) {
      if (_isPlaying && !_isPaused) {
        _currentTime += 0.1;
        _timeController.add(_currentTime);
        
        if (_duration > 0 && _currentTime >= _duration) {
          stop();
        }
      }
    });
  }
  
  void _stopProgressTimer() {
    _progressTimer?.cancel();
    _progressTimer = null;
  }
  
  // 状态查询
  PlayerState get currentState => _currentState;
  double get currentTime => _currentTime;
  double get duration => _duration;
  MediaInfo? get mediaInfo => _mediaInfo;
  bool get isPlaying => _isPlaying;
  bool get isPaused => _isPaused;
  
  // 流监听
  Stream<PlayerState> get stateStream => _stateController.stream;
  Stream<double> get timeStream => _timeController.stream;
  Stream<MediaInfo> get mediaInfoStream => _mediaInfoController.stream;
  Stream<String> get errorStream => _errorController.stream;
  
  void dispose() {
    _stopProgressTimer();
    _stateController.close();
    _timeController.close();
    _mediaInfoController.close();
    _errorController.close();
  }
}
